﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using Model.Manager;
using Model.Manager.DataBase;
using Model.Platform.PhysicalData;

namespace BML.Infrastructure.Platform
{
    /// <summary>
    ///     系统配置
    ///     保存在数据库，初次调用进行初始
    ///     TODO：保存在什么地方，如何全局读取
    /// </summary>
    public class SystemicSetting
    {
        /// <summary>
        ///     实例化对象，按照属性名称正序排序
        /// Desc    
        /// Id      
        /// KeyWord 
        /// Status  
        /// Type    
        /// Value   
        /// </summary>
        /// <param name="props"></param>
        /// <returns></returns>
        private Setting NewSetting(params object[] props)
        {
            return new Setting
            {
                Desc = (String)props[0],
                Id = (Guid)props[1],
                KeyWord = (String)props[2],
                Status = (Int32)props[3],
                Type = (Int32)props[4],
                Value = (String)props[5]
            };
        }

        /// <summary>
        ///     查询全部信息（任何状态）
        /// </summary>
        /// <returns></returns>
        public IList<Setting> PlatformConfig()
        {
            using (IDbContext db = ContextFactory.GetPlatformConnect())
            {
                return db.GetOperator<Setting>().CreateQuery().ToList();
            }
        }
        public Dictionary<String, String> PlatformConfigByDictionary()
        {
            using (IDbContext db = ContextFactory.GetPlatformConnect())
            {
                return db.GetOperator<Setting>().CreateQuery().ToDictionary(m => m.KeyWord, m => m.Value);
            }
        }


        /// <summary>
        ///   生成数据  Dict[KEY]:"keyword-type"
        ///   数据库中已经产生的变更，不再变动
        /// </summary>
        /// <param name="dictionary"></param>
        public void SetPlatformConfig(Dictionary<String, String> dictionary)
        {
            using (IDbContext db = ContextFactory.GetPlatformConnect())
            {
                foreach (var dict in dictionary)
                {
                    String keyword = dict.Key.Split('-')[0];
                    if (CanInsert(db, keyword))
                    {
                        db.GetOperator<Setting>().Create(
                            NewSetting(
                            "描述",
                            Guid.NewGuid(),
                            keyword,
                            OpertorStatusCode.Display,
                            Int32.Parse(dict.Key.Split('-')[1]),
                            dict.Value));
                    }

                }
                db.SaveAllChange();
            }
        }


        /// <summary>
        ///     当前字键是否可以作为新数据插入。
        /// </summary>
        /// <param name="db"></param>
        /// <param name="key">字键Key</param>
        /// <returns></returns>
        private bool CanInsert(IDbContext db, String key)
        {
           // return db.Queryable<Setting>().SingleOrDefault(m => m.KeyWord == key) == null;

            return !db.Queryable<Setting>().Any(m => m.KeyWord == key);
        }






        /// <summary>
        ///     更新单一配置信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void UpdPlatformConfig(Guid id, String key, String value)
        {
            using (IDbContext db = ContextFactory.GetPlatformConnect())
            {
                var obj = db.GetOperator<Setting>().Retrieve(id);
                obj.KeyWord = key;
                obj.Value = value;
                db.GetOperator<Setting>().Modify(obj);
                db.SaveAllChange();
            }
        }

        public void ChangePlatformConfig(Dictionary<String, String> dict)
        {
            using (IDbContext db = ContextFactory.GetPlatformConnect())
            {
                var op = db.GetOperator<Setting>();

                foreach (var d in dict)
                {
                    var obj = op.CreateQuery().Single(m => m.KeyWord == d.Key);
                    obj.Value = d.Value;
                    obj.Status = OpertorStatusCode.Changed;
                    op.Modify(obj);
                }
                db.SaveAllChange();
            }
        }

        /// <summary>
        ///     删除单一配置信息
        /// </summary>
        /// <param name="id"></param>
        public void DelPlatformConfig(Guid id)
        {
            using (IDbContext db = ContextFactory.GetPlatformConnect())
            {
                db.GetOperator<Setting>().Destroy(db.GetOperator<Setting>().Retrieve(id));
                db.SaveAllChange();
            }
        }

        public void ClearConfig()
        {
            using (IDbContext db = ContextFactory.GetPlatformConnect())
            {
                var list = db.Queryable<Setting>().ToList();
                foreach (var setting in list)
                {
                    db.GetOperator<Setting>().Destroy(setting);
                }
                db.SaveAllChange();
            }
        }


    }
}